<?php

namespace app\admin\logic;


use support\Exception\ApiException;
use support\Model\ActionLogModel;
use support\Service\LoginService;
use support\Service\UserService;
use Tinywan\Captcha\Captcha;

class LoginLogic extends BaseLogic
{

    public function __construct()
    {
        self::$service = new UserService();
    }

    public static function captcha()
    {
        $result = LoginService::captcha();
        return message($result);
    }

    public static function login()
    {
        // 请求参数
        $param = request()->post();
        // 登录账号
        $username = trim($param['username'] ?? '');
        if (!$username) {
            throw  new ApiException('登录账号不能为空');
        }
        // 登录密码
        $password = trim($param['password'] ?? '');
        if (!$password) {
            throw  new ApiException('登录密码不能为空');
        }
        // 验证码校验
        $key = trim($param['key'] ?? '');
        // 验证码
        $captcha = trim($param['captcha'] ?? '');
        if (!$key || !$captcha) {
            throw  new ApiException('请输入正确的验证码');
        }
        if (Captcha::check($captcha, $key) === false) {
            throw  new ApiException('请输入正确的验证码');
        }
        $info = self::$service::getInfoByWhere([['username', '=', $username]]);
        if (!$info) throw  new ApiException('登录账号不存在');
        // 使用状态校验
        if ($info['status'] != 1) {
            throw  new ApiException('帐号已被禁用');
        }
        // 密码校验
        $password = get_password($password . $username);
        if ($password != $info['password']) {
            throw  new ApiException('登录密码不正确');
        }
        $result = \Tinywan\Jwt\JwtToken::generateToken($info);
        //创建登录日志
        self::record();
        // 结果返回
        return message($result);
    }

    /**
     * 注销系统
     * @return void
     */
    public static function Logout()
    {

        return self::record(2);
    }

    /**
     * 记录日志
     * @param $type
     * @return array
     */
    public static function record($type = 1)
    {
        $data = [
            'username' => '管理员',
            'plugin' => request()->plugin,
            'module' => request()->app,
            'controller' => request()->controller,
            'action' => request()->action,
            'method' => request()->method(),
            'url' => request()->fullUrl(), // 获取完成URL
            'param' => request()->all() ? json_encode(request()->all()) : '',
            'title' => $type == 1 ? '登录系统' : '退出登录',
            'type' => $type,
            'content' => '',
            'ip' => request()->getRemoteIp(),
            'user_agent' => request()->header('HTTP_USER_AGENT') ?: '1',
            'create_time' => time(),
        ];
        return (new ActionLogModel())->insertOne($data);
    }
}
